package com.android.sgzcommon.dialog;

import android.content.Context;
import android.os.Bundle;
import android.text.TextUtils;

import com.android.sgzcommon.dialog.entity.TextListItem;
import com.android.sgzcommon.recycleview.BaseRecyclerviewAdapter;
import com.android.sgzcommon.recycleview.adapter.BaseTextListAdapter;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author sgz
 * @date 2020/6/30
 */
public abstract class BaseTextListDialog<V extends TextListItem> extends BaseListDialog<V> {

    private List<V> mAllItems;

    /**
     * @param data
     * @param response
     */
    protected abstract void loadTextList(Map<String, String> data, OnLoadListResponse response);

    @Override
    protected void filterChanged(String filter, Map<String, String> data, OnLoadListResponse<V> response) {
        showItems(filter,response);
    }

    protected void loadList(Map<String, String> data, OnLoadListResponse response) {
        loadTextList(data, new OnLoadListResponse() {
            @Override
            public void onStart() {
                response.onStart();
            }

            @Override
            public void onSuccess(List items) {
                mAllItems.clear();
                if (items != null) {
                    mAllItems.addAll(items);
                }
                String filter = "";
                if (mEtFilter != null){
                    filter = mEtFilter.getText().toString();
                }
                showItems(filter,response);
            }

            @Override
            public void onFailed() {
                response.onFailed();
            }
        });
    }

    /**
     *
     * @param filter
     * @param response
     */
    private void showItems(String filter,OnLoadListResponse<V> response) {
        if (TextUtils.isEmpty(filter)) {
            response.onSuccess(mAllItems);
        } else {
            List<V> showItems = new ArrayList<>();
            for (int i = 0; i < mAllItems.size(); i++) {
                if (mAllItems.get(i).getItemName().contains(filter)) {
                    showItems.add(mAllItems.get(i));
                }
                response.onSuccess(showItems);
            }
        }
    }

    @Override
    protected BaseRecyclerviewAdapter getAdapter(List<V> items) {
        return new BaseTextListAdapter(mContext, items);
    }

    public BaseTextListDialog(Context context) {
        super(context);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mAllItems = new ArrayList<>();
    }

    /**
     * @param enable
     */
    public void setFilter(boolean enable) {
        setFilterEnable(enable);
    }
}
